// 短语列表主应用逻辑
document.addEventListener('DOMContentLoaded', async () => {
  // DOM 元素
  const navLinks = document.querySelectorAll('.nav-link');
  const searchInput = document.getElementById('search-input');
  const searchBtn = document.querySelector('.search-btn');
  const clearSearchBtn = document.querySelector('.clear-search-btn');
  const addPhraseBtn = document.getElementById('add-btn');
  const phraseModal = document.getElementById('phrase-modal');
  const modalTitle = document.getElementById('modal-title');
  const closeBtn = document.querySelector('.close-btn');
  const cancelBtn = document.querySelector('.cancel-btn');
  const phraseForm = document.querySelector('.word-form');
  const phraseInput = document.getElementById('phrase');
  const translationInput = document.getElementById('translation');
  const exampleInput = document.getElementById('example');
  const phraseList = document.getElementById('phrase-list');
  const emptyMessage = document.querySelector('.empty-message');
  const filterBtns = document.querySelectorAll('.filter-btn');
  
  // 管理功能相关元素
  const manageBtn = document.getElementById('manage-btn');
  const manageActions = document.getElementById('manage-actions');
  const deleteSelectedBtn = document.getElementById('delete-selected-btn');
  const finishManageBtn = document.getElementById('finish-manage-btn');
  const selectAllCheckbox = document.getElementById('select-all-checkbox');
  
  // 视图切换相关元素
  const switchViewBtn = document.getElementById('switch-view-btn');
  const phraseTable = document.getElementById('phrase-table');
  const phraseCardList = document.getElementById('phrase-card-list');
  
  // 分页相关元素
  const firstPageBtn = document.getElementById('first-page');
  const prevPageBtn = document.getElementById('prev-page');
  const nextPageBtn = document.getElementById('next-page');
  const lastPageBtn = document.getElementById('last-page');
  const pageNumbers = document.getElementById('page-numbers');
  const jumpPageInput = document.getElementById('jump-page');
  const jumpBtn = document.getElementById('jump-btn');
  const pageInfoText = document.getElementById('page-info-text');
  
  let currentEditId = null;
  let currentFilter = 'newest';
  let currentPage = 1;
  const itemsPerPage = 10;
  
  let isCardView = false;
  
  /**
   * 检查用户是否已登录
   * @returns {boolean} 返回登录状态
   */
  const checkLoginStatus = () => {
    try {
      let userStr = localStorage.getItem('user');
      let isLoggedIn = localStorage.getItem('isLoggedIn');
      
      if (!userStr || isLoggedIn !== 'true') {
        userStr = sessionStorage.getItem('user');
        isLoggedIn = sessionStorage.getItem('isLoggedIn');
      }
      
      return userStr && isLoggedIn === 'true';
    } catch (error) {
      return false;
    }
  };
  
  /**
   * 获取当前用户信息
   * @returns {Object|null} 返回用户信息或null
   */
  const getCurrentUser = () => {
    try {
      let userStr = localStorage.getItem('user');
      if (!userStr) {
        userStr = sessionStorage.getItem('user');
      }
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      return null;
    }
  };
  
  /**
   * 更新导航栏用户显示
   */
  const updateNavbarUserDisplay = () => {
    const navLogin = document.getElementById('nav-login');
    const userDropdown = document.getElementById('user-dropdown');
    const navUsername = document.getElementById('nav-username');
    const navUserAvatar = document.getElementById('nav-user-avatar');
    
    if (checkLoginStatus()) {
      const user = getCurrentUser();
      if (user && navLogin && userDropdown && navUsername) {
        navLogin.style.display = 'none';
        userDropdown.style.display = 'block';
        navUsername.textContent = user.nickname;
        
        if (navUserAvatar) {
          if (user.avatar && user.avatar !== 'img/default-avatar.png') {
            let avatarUrl = user.avatar;
            const finalAvatarUrl = `../${avatarUrl}?t=${Date.now()}`;
            navUserAvatar.src = finalAvatarUrl;
            
            navUserAvatar.onerror = () => {
              navUserAvatar.src = '../img/default-avatar.png';
              navUserAvatar.onerror = null;
            };
          } else {
            navUserAvatar.src = '../img/default-avatar.png';
          }
        }
      }
    } else {
      if (navLogin && userDropdown) {
        navLogin.style.display = 'block';
        userDropdown.style.display = 'none';
      }
    }
  };
  
  /**
   * 用户登出
   */
  const logout = () => {
    localStorage.removeItem('user');
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('rememberLogin');
    
    sessionStorage.removeItem('user');
    sessionStorage.removeItem('isLoggedIn');
    
    updateNavbarUserDisplay();
    window.location.href = 'account.html';
  };
  
  /**
   * 显示登录提示对话框
   * @param {string} action - 操作名称
   */
  const showLoginPrompt = (action = '操作') => {
    showActionDialog(
      '需要登录',
      `登录后才能进行${action}`,
      {
        actionText: '登录',
        actionType: 'primary',
        onAction: () => {
          window.location.href = 'account.html';
        },
        onCancel: () => {}
      }
    );
  };
  
  /**
   * 权限检查装饰器
   * @param {Function} callback - 需要权限的回调函数
   * @param {string} action - 操作名称
   * @returns {Function} 包装后的函数
   */
  const requireLogin = (callback, action = '操作') => {
    return (...args) => {
      if (!checkLoginStatus()) {
        showLoginPrompt(action);
        return;
      }
      return callback(...args);
    };
  };
  
  // 初始化数据
  try {
    await PhraseData.initializeData();
  } catch (error) {
    // console.error('Failed to initialize data:', error);
  }
  
  /**
   * 初始化应用
   */
  const initApp = async () => {
    setupEventListeners();
    updateNavbarUserDisplay();
    checkAndSetInitialView();
    await renderPhraseList();
  };
  
  /**
   * 检测窗口宽度并设置初始视图
   */
  const checkAndSetInitialView = () => {
    const windowWidth = window.innerWidth;
    
    if (windowWidth <= 720) {
      if (!isCardView) {
        isCardView = true;
        phraseTable.style.display = 'none';
        phraseCardList.style.display = 'block';
        switchViewBtn.innerHTML = '<img src="../img/icon-cards.svg" alt="切换视图" width="16" height="16">';
      }
    } else {
      if (isCardView) {
        isCardView = false;
        phraseTable.style.display = 'table';
        phraseCardList.style.display = 'none';
        switchViewBtn.innerHTML = '<img src="../img/icon-table.svg" alt="切换视图" width="16" height="16">';
      }
    }
  };
  
  /**
   * 切换视图
   */
  const toggleView = () => {
    isCardView = !isCardView;
    
    if (isCardView) {
      phraseTable.style.display = 'none';
      phraseCardList.style.display = 'block';
      switchViewBtn.innerHTML = '<img src="../img/icon-cards.svg" alt="切换视图" width="16" height="16">';
    } else {
      phraseTable.style.display = 'table';
      phraseCardList.style.display = 'none';
      switchViewBtn.innerHTML = '<img src="../img/icon-table.svg" alt="切换视图" width="16" height="16">';
    }
    
    renderPhraseList();
  };
  
  /**
   * 筛选和排序短语
   * @param {string} filter - 筛选条件
   * @returns {Promise<Array>} 返回筛选和排序后的短语数组
   */
  const filterAndSortPhrases = async (filter = currentFilter) => {
    let phrases = PhraseData.getAllPhrases();
    
    if (!phrases || phrases.length === 0) {
      try {
        phrases = await PhraseData.refreshCache();
      } catch (error) {
        phrases = [];
      }
    }
    
    phrases = [...phrases];
    
    switch (filter) {
      case 'memorized':
        phrases = phrases.filter(phrase => phrase.memorized === true);
        break;
      case 'unmemorized':
        phrases = phrases.filter(phrase => phrase.memorized === false);
        break;
      case 'oldest':
        phrases = phrases.sort((a, b) => {
          const dateA = new Date(a.createDate);
          const dateB = new Date(b.createDate);
          return dateA - dateB;
        });
        break;
      case 'newest':
      default:
        phrases = phrases.sort((a, b) => {
          const dateA = new Date(a.createDate);
          const dateB = new Date(b.createDate);
          return dateB - dateA;
        });
        break;
    }
    
    return phrases;
  };
  
  /**
   * 对给定的短语数组应用当前筛选
   * @param {Array} phrases - 短语数组
   * @returns {Array} 返回筛选后的短语数组
   */
  const applyCurrentFilter = (phrases) => {
    const phrasesCopy = [...phrases];
    
    switch (currentFilter) {
      case 'memorized':
        return phrasesCopy.filter(phrase => phrase.memorized === true);
      case 'unmemorized':
        return phrasesCopy.filter(phrase => phrase.memorized === false);
      case 'oldest':
        return phrasesCopy.sort((a, b) => {
          const dateA = new Date(a.createDate);
          const dateB = new Date(b.createDate);
          return dateA - dateB;
        });
      case 'newest':
      default:
        return phrasesCopy.sort((a, b) => {
          const dateA = new Date(a.createDate);
          const dateB = new Date(b.createDate);
          return dateB - dateA;
        });
    }
  };
  
  /**
   * 渲染短语列表
   * @param {Array|null} phrases - 要渲染的短语数组
   */
  const renderPhraseList = async (phrases = null) => {
    const allPhrases = phrases || await filterAndSortPhrases();
    const totalPages = Math.ceil(allPhrases.length / itemsPerPage);
    
    updatePhraseStatistics(allPhrases);
    
    if (currentPage > totalPages && totalPages > 0) {
      currentPage = totalPages;
    } else if (currentPage < 1) {
      currentPage = 1;
    }
    
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const phrasesToRender = allPhrases.slice(startIndex, endIndex);
    
    if (allPhrases.length === 0) {
      phraseList.innerHTML = '';
      phraseCardList.innerHTML = '';
      emptyMessage.classList.remove('hidden');
      document.querySelector('.pagination-container').style.display = 'none';
      return;
    }
    
    emptyMessage.classList.add('hidden');
    document.querySelector('.pagination-container').style.display = 'flex';
    
    if (isCardView) {
      renderCardView(phrasesToRender, startIndex);
    } else {
      renderTableView(phrasesToRender, startIndex);
    }
    
    renderPagination(totalPages, allPhrases.length);
  };
  
  /**
   * 更新短语统计信息
   * @param {Array} phrases - 短语数组
   */
  const updatePhraseStatistics = (phrases) => {
    const totalPhrases = phrases.length;
    const rememberedPhrases = phrases.filter(phrase => phrase.memorized === true).length;
    const unrememberedPhrases = totalPhrases - rememberedPhrases;
    
    const statisticsElement = document.getElementById('phrase-count-statistics');
    if (statisticsElement) {
      statisticsElement.textContent = `共 ${totalPhrases} 个短语，未记住 ${unrememberedPhrases} 个，已记住 ${rememberedPhrases} 个`;
    }
  };
  
  // 渲染表格视图
  const renderTableView = (phrasesToRender, startIndex) => {
    phraseList.innerHTML = phrasesToRender.map((phrase, index) => {
      const serialNumber = String(startIndex + index + 1).padStart(5, '0');
      return `
        <tr class="${phrase.memorized ? 'memorized' : ''}" data-id="${phrase.id}">
          <td class="checkbox-column" style="display: none;">
            <input type="checkbox" class="word-checkbox" />
          </td>
          <td>${serialNumber}</td>
          <td>${phrase.phrase}</td>
          <td>${phrase.translation.replace(/\n/g, '<br>')}</td>
          <td>${phrase.example.replace(/\n/g, '<br>')}</td>
          <td>
            <div class="actions">
              <button class="edit-btn" title="编辑">
                <img src="../img/edit.svg" alt="编辑" class="action-icon">
              </button>
              <button class="delete-btn" title="删除">
                <img src="../img/delete.svg" alt="删除" class="action-icon">
              </button>
              <button class="memorized-btn ${phrase.memorized ? 'memorized' : 'unmemorized'}">${phrase.memorized ? '已记住' : '未记住'}</button>
            </div>
          </td>
        </tr>
      `;
    }).join('');
  };
  
  // 渲染卡片视图
  const renderCardView = (phrasesToRender, startIndex) => {
    phraseCardList.innerHTML = phrasesToRender.map((phrase, index) => {
      const serialNumber = String(startIndex + index + 1).padStart(5, '0');
      return `
        <div class="word-card ${phrase.memorized ? 'memorized' : ''}" data-id="${phrase.id}">
          <div class="word-card-number">${serialNumber}</div>
          <input type="checkbox" class="word-card-checkbox word-checkbox" />
          <div class="word-card-content">
            <div class="word-card-main">
              <span class="word-card-word">${phrase.phrase}</span>
            </div>
            <div class="word-card-translation">${phrase.translation}</div>
            <div class="word-card-example">${phrase.example}</div>
            <div class="word-card-actions">
              <button class="edit-btn" title="编辑">
                <img src="../img/edit.svg" alt="编辑" class="action-icon">
              </button>
              <button class="delete-btn" title="删除">
                <img src="../img/delete.svg" alt="删除" class="action-icon">
              </button>
              <button class="memorized-btn ${phrase.memorized ? 'memorized' : 'unmemorized'}">${phrase.memorized ? '已记住' : '未记住'}</button>
            </div>
          </div>
        </div>
      `;
    }).join('');
  };
  
  // 渲染分页器
  const renderPagination = (totalPages, totalItems) => {
    pageInfoText.textContent = `第 ${currentPage} 页，共 ${totalPages} 页`;
    
    firstPageBtn.disabled = currentPage === 1;
    prevPageBtn.disabled = currentPage === 1;
    nextPageBtn.disabled = currentPage === totalPages;
    lastPageBtn.disabled = currentPage === totalPages;
    
    jumpPageInput.max = totalPages;
    
    renderPageNumbers(totalPages);
  };
  
  // 渲染页码按钮
  const renderPageNumbers = (totalPages) => {
    pageNumbers.innerHTML = '';
    
    if (totalPages <= 10) {
      for (let i = 1; i <= totalPages; i++) {
        const pageBtn = createPageButton(i);
        pageNumbers.appendChild(pageBtn);
      }
    } else {
      const startPage = Math.max(1, currentPage - 4);
      const endPage = Math.min(totalPages, currentPage + 4);
      
      if (startPage > 1) {
        pageNumbers.appendChild(createPageButton(1));
        if (startPage > 2) {
          pageNumbers.appendChild(createEllipsis());
        }
      }
      
      for (let i = startPage; i <= endPage; i++) {
        const pageBtn = createPageButton(i);
        pageNumbers.appendChild(pageBtn);
      }
      
      if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
          pageNumbers.appendChild(createEllipsis());
        }
        pageNumbers.appendChild(createPageButton(totalPages));
      }
    }
  };
  
  /**
   * 创建页码按钮
   */
  const createPageButton = (pageNum) => {
    const btn = document.createElement('button');
    btn.className = `pagination-btn ${pageNum === currentPage ? 'active' : ''}`;
    btn.textContent = pageNum;
    btn.addEventListener('click', async () => {
      currentPage = pageNum;
      await renderPhraseList();
    });
    return btn;
  };
  
  /**
   * 创建省略号元素
   */
  const createEllipsis = () => {
    const span = document.createElement('span');
    span.textContent = '...';
    span.style.padding = '8px 4px';
    span.style.color = '#666';
    return span;
  };
  
  /**
   * 设置事件监听器
   */
  const setupEventListeners = () => {
    // 导航栏事件
    navLinks.forEach(link => {
      link.addEventListener('click', (e) => {
        if (link.id === 'nav-login') {
          return;
        }
        
        e.preventDefault();
        
        const page = link.dataset.page;
        if (page === 'vocabulary-test') {
          window.location.href = 'vocabulary-test.html';
        } else if (link.href && !link.href.includes('#')) {
          window.location.href = link.href;
        }
      });
    });
    
    // 搜索短语
    searchBtn.addEventListener('click', async () => {
      const query = searchInput.value.trim();
      let results = await PhraseData.searchPhrases(query);
      
      if (query && results.length > 0) {
        results = applyCurrentFilter(results);
      }
      
      currentPage = 1;
      await renderPhraseList(results);
      
      if (query) {
        clearSearchBtn.classList.remove('hidden');
      }
    });
    
    searchInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        searchBtn.click();
      }
    });
    
    // 清空搜索
    clearSearchBtn.addEventListener('click', async () => {
      searchInput.value = '';
      currentPage = 1;
      await renderPhraseList();
      clearSearchBtn.classList.add('hidden');
    });
    
    // 筛选按钮事件
    filterBtns.forEach(btn => {
      btn.addEventListener('click', async () => {
        filterBtns.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        
        currentFilter = btn.dataset.filter;
        currentPage = 1;
        
        await renderPhraseList();
      });
    });
    
    // 分页器事件
    firstPageBtn.addEventListener('click', async () => {
      currentPage = 1;
      await renderPhraseList();
    });
    
    prevPageBtn.addEventListener('click', async () => {
      if (currentPage > 1) {
        currentPage--;
        await renderPhraseList();
      }
    });
    
    nextPageBtn.addEventListener('click', async () => {
      const allPhrases = await filterAndSortPhrases();
      const totalPages = Math.ceil(allPhrases.length / itemsPerPage);
      if (currentPage < totalPages) {
        currentPage++;
        await renderPhraseList();
      }
    });
    
    lastPageBtn.addEventListener('click', async () => {
      const allPhrases = await filterAndSortPhrases();
      const totalPages = Math.ceil(allPhrases.length / itemsPerPage);
      currentPage = totalPages;
      await renderPhraseList();
    });
    
    jumpBtn.addEventListener('click', async () => {
      const targetPage = parseInt(jumpPageInput.value);
      const allPhrases = await filterAndSortPhrases();
      const totalPages = Math.ceil(allPhrases.length / itemsPerPage);
      if (targetPage >= 1 && targetPage <= totalPages) {
        currentPage = targetPage;
        await renderPhraseList();
        jumpPageInput.value = '';
      }
    });
    
    jumpPageInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        jumpBtn.click();
      }
    });
    
    // 视图切换按钮事件
    if (switchViewBtn) {
      switchViewBtn.addEventListener('click', () => {
        toggleView();
      });
    }
    
    // 管理功能事件
    if (manageBtn) {
      manageBtn.addEventListener('click', requireLogin(() => {
        manageBtn.style.display = 'none';
        manageActions.style.display = 'flex';
        
        if (phraseTable) {
          phraseTable.classList.add('manage-mode');
        }
        
        const paginationContainer = document.querySelector('.pagination-container');
        if (paginationContainer) {
          paginationContainer.style.display = 'none';
        }
        
        if (switchViewBtn) {
          switchViewBtn.style.display = 'none';
        }
        
        showCheckboxColumn();
      }, '管理短语'));
    }
    
    if (deleteSelectedBtn) {
      deleteSelectedBtn.addEventListener('click', requireLogin(() => {
        deleteSelectedPhrases();
      }, '删除选中短语'));
    }
    
    if (finishManageBtn) {
      finishManageBtn.addEventListener('click', () => {
        exitManageMode();
      });
    }
    
    // 全选复选框事件
    if (selectAllCheckbox) {
      selectAllCheckbox.addEventListener('change', (e) => {
        const checkboxes = document.querySelectorAll('.word-checkbox');
        checkboxes.forEach(checkbox => {
          checkbox.checked = e.target.checked;
        });
      });
    }
    
    // 登出按钮事件
    const logoutBtn = document.getElementById('logout-btn');
    if (logoutBtn) {
      logoutBtn.addEventListener('click', logout);
    }
    
    // 添加新短语按钮
    addPhraseBtn.addEventListener('click', requireLogin(() => {
      openAddPhraseModal();
    }, '添加短语'));
    
    // 短语列表操作（编辑、删除、标记）
    phraseList.addEventListener('click', async (e) => {
      const target = e.target;
      const row = target.closest('tr');
      
      if (!row) return;
      
      const id = row.dataset.id;
      
      const editBtn = target.closest('.edit-btn');
      const deleteBtn = target.closest('.delete-btn');
      const memorizedBtn = target.closest('.memorized-btn');
      
      if (editBtn) {
        requireLogin(async () => {
          await openEditPhraseModal(id);
        }, '编辑短语')();
      } else if (deleteBtn) {
        requireLogin(async () => {
          showDeleteDialog(
            '确定要删除这个短语吗？此操作不可撤销。',
            async () => {
              try {
                await PhraseData.deletePhrase(id);
                await renderPhraseList();
                showConfirmDialog('删除成功', '短语已成功删除');
              } catch (error) {
                showConfirmDialog('删除失败', '删除短语失败，请重试');
              }
            }
          );
        }, '删除短语')();
      } else if (memorizedBtn) {
        requireLogin(async () => {
          await PhraseData.toggleMemorized(id);
          await renderPhraseList();
        }, '标记短语')();
      }
    });
    
    // 卡片视图操作事件
    phraseCardList.addEventListener('click', async (e) => {
      const target = e.target;
      const card = target.closest('.word-card');
      
      if (!card) return;
      
      const id = card.dataset.id;
      
      const editBtn = target.closest('.edit-btn');
      const deleteBtn = target.closest('.delete-btn');
      const memorizedBtn = target.closest('.memorized-btn');
      
      if (editBtn) {
        requireLogin(async () => {
          await openEditPhraseModal(id);
        }, '编辑短语')();
      } else if (deleteBtn) {
        requireLogin(async () => {
          showDeleteDialog(
            '确定要删除这个短语吗？此操作不可撤销。',
            async () => {
              try {
                await PhraseData.deletePhrase(id);
                await renderPhraseList();
                showConfirmDialog('删除成功', '短语已成功删除');
              } catch (error) {
                showConfirmDialog('删除失败', '删除短语失败，请重试');
              }
            }
          );
        }, '删除短语')();
      } else if (memorizedBtn) {
        requireLogin(async () => {
          await PhraseData.toggleMemorized(id);
          await renderPhraseList();
        }, '标记短语')();
      }
    });
    
    // 模态框关闭
    closeBtn.addEventListener('click', closeModal);
    cancelBtn.addEventListener('click', closeModal);
    
    // 表单提交
    phraseForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      
      const phraseData = {
        phrase: phraseInput.value.trim(),
        translation: translationInput.value.trim(),
        example: exampleInput.value.trim()
      };
      
      try {
        let newPhraseId = null;
        
        if (currentEditId) {
          await PhraseData.updatePhrase(currentEditId, phraseData);
        } else {
          const newPhrase = await PhraseData.addPhrase(phraseData);
          newPhraseId = newPhrase.id;
        }
        
        await renderPhraseList();
        closeModal();
        
        if (newPhraseId) {
          highlightNewPhraseRow(newPhraseId);
        }
      } catch (error) {
        alert('保存短语失败，请重试');
      }
    });
  };
  
  /**
   * 打开添加短语模态框
   */
  const openAddPhraseModal = () => {
    modalTitle.textContent = '添加新短语';
    phraseForm.reset();
    currentEditId = null;
    phraseModal.classList.remove('hidden');
    phraseInput.focus();
  };
  
  /**
   * 打开编辑短语模态框
   */
  const openEditPhraseModal = async (id) => {
    try {
      let phrases = PhraseData.getAllPhrases();
      
      if (!phrases || phrases.length === 0) {
        phrases = await PhraseData.refreshCache();
      }
      
      const phrase = phrases.find(p => p.id === id);
      
      if (phrase) {
        modalTitle.textContent = '编辑短语';
        phraseInput.value = phrase.phrase;
        translationInput.value = phrase.translation;
        exampleInput.value = phrase.example;
        
        currentEditId = id;
        phraseModal.classList.remove('hidden');
        phraseInput.focus();
      }
    } catch (error) {
      alert('打开编辑窗口失败，请重试');
    }
  };
  
  /**
   * 关闭模态框
   */
  const closeModal = () => {
    phraseModal.classList.add('hidden');
    phraseForm.reset();
    currentEditId = null;
  };
  
  /**
   * 为新添加的短语行添加高亮动画效果
   */
  const highlightNewPhraseRow = (phraseId) => {
    setTimeout(() => {
      const selector = isCardView ? `.word-card[data-id="${phraseId}"]` : `tr[data-id="${phraseId}"]`;
      const phraseElement = document.querySelector(selector);
      if (phraseElement) {
        phraseElement.classList.add('new-word-highlight');
        
        setTimeout(() => {
          phraseElement.classList.remove('new-word-highlight');
        }, 600);
      }
    }, 100);
  };
  
  /**
   * 显示复选框列
   */
  const showCheckboxColumn = () => {
    const checkboxColumns = document.querySelectorAll('.checkbox-column');
    checkboxColumns.forEach(col => {
      col.style.display = 'table-cell';
    });
    
    const cardCheckboxes = document.querySelectorAll('.word-card-checkbox');
    cardCheckboxes.forEach(checkbox => {
      checkbox.classList.add('show');
    });
  };
  
  /**
   * 隐藏复选框列
   */
  const hideCheckboxColumn = () => {
    const checkboxColumns = document.querySelectorAll('.checkbox-column');
    checkboxColumns.forEach(col => {
      col.style.display = 'none';
    });
    
    const cardCheckboxes = document.querySelectorAll('.word-card-checkbox');
    cardCheckboxes.forEach(checkbox => {
      checkbox.classList.remove('show');
    });
    
    const checkboxes = document.querySelectorAll('.word-checkbox');
    checkboxes.forEach(checkbox => {
      checkbox.checked = false;
    });
  };
  
  /**
   * 删除选中的短语
   */
  const deleteSelectedPhrases = async () => {
    const selectedCheckboxes = document.querySelectorAll('.word-checkbox:checked');
    
    if (selectedCheckboxes.length === 0) {
      showConfirmDialog('提示', '请先选择要删除的短语');
      return;
    }
    
    const selectedIds = Array.from(selectedCheckboxes).map(checkbox => {
      const tableRow = checkbox.closest('tr');
      const cardElement = checkbox.closest('.word-card');
      
      if (tableRow) {
        return tableRow.dataset.id;
      } else if (cardElement) {
        return cardElement.dataset.id;
      }
      return null;
    }).filter(id => id !== null);
    
    showDeleteDialog(
      `确定要删除选中的 ${selectedIds.length} 个短语吗？此操作不可撤销。`,
      async () => {
        try {
          for (const id of selectedIds) {
            await PhraseData.deletePhrase(id);
          }
          
          exitManageMode();
          await renderPhraseList();
          showConfirmDialog('成功', `已成功删除 ${selectedIds.length} 个短语`);
        } catch (error) {
          showConfirmDialog('错误', '删除短语失败，请重试');
        }
      }
    );
  };
  
  /**
   * 退出管理模式
   */
  const exitManageMode = () => {
    manageBtn.style.display = 'block';
    manageActions.style.display = 'none';
    
    if (phraseTable) {
      phraseTable.classList.remove('manage-mode');
    }
    
    const paginationContainer = document.querySelector('.pagination-container');
    if (paginationContainer) {
      paginationContainer.style.display = 'flex';
    }
    
    if (switchViewBtn) {
      switchViewBtn.style.display = 'block';
    }
    
    hideCheckboxColumn();
  };
  
  // 初始化应用
  await initApp();
});
